<template>
  <div class="book-list-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="6" :md="5" :lg="4" class="filter-wrapper">
        <filter-sidebar @filter-change="handleFilterChange" />
      </el-col>
      <el-col :xs="24" :sm="18" :md="19" :lg="20">
        <div class="list-header">
          <div class="search-sort-container">
            <el-input
              v-model="searchQuery"
              placeholder="Search books..."
              prefix-icon="el-icon-search"
              clearable
              @input="handleSearch"
              class="search-input"
            />
            <el-select v-model="sortOption" placeholder="Sort by" @change="handleSort" class="sort-select">
              <el-option label="Title (A-Z)" value="title-asc" />
              <el-option label="Title (Z-A)" value="title-desc" />
              <el-option label="Author (A-Z)" value="author-asc" />
              <el-option label="Author (Z-A)" value="author-desc" />
              <el-option label="Newest" value="date-desc" />
              <el-option label="Oldest" value="date-asc" />
            </el-select>
          </div>
          <div class="view-toggle">
            <el-radio-group v-model="viewMode" size="small">
              <el-radio-button label="grid">
                <i class="el-icon-s-grid"></i>
              </el-radio-button>
              <el-radio-button label="list">
                <i class="el-icon-menu"></i>
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <el-empty v-if="filteredBooks.length === 0" description="No books found" />

        <div :class="['book-list', viewMode]" v-else>
          <book-card 
            v-for="book in paginatedBooks" 
            :key="book.id" 
            :book="book"
            :view-mode="viewMode"
            @click="viewBookDetails(book.id)"
          />
        </div>

        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="filteredBooks.length"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import FilterSidebar from '@/components/FilterSidebar.vue'
import BookCard from '@/components/BookCard.vue'

export default {
  name: 'BookList',
  components: {
    FilterSidebar,
    BookCard
  },
  data() {
    return {
      books: [],
      searchQuery: '',
      sortOption: 'title-asc',
      filters: {},
      viewMode: 'grid',
      currentPage: 1,
      pageSize: 12,
      loading: false
    }
  },
  computed: {
    filteredBooks() {
      // Apply filters
      let result = [...this.books]
      
      // Apply search filter
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(book => 
          book.title.toLowerCase().includes(query) || 
          book.author.toLowerCase().includes(query) ||
          (book.description && book.description.toLowerCase().includes(query))
        )
      }
      
      // Apply category filters
      if (this.filters.categories && this.filters.categories.length) {
        result = result.filter(book => 
          this.filters.categories.some(category => book.categories.includes(category))
        )
      }
      
      // Apply status filters
      if (this.filters.status && this.filters.status.length) {
        result = result.filter(book => this.filters.status.includes(book.status))
      }
      
      // Apply date range filter
      if (this.filters.dateRange) {
        const [min, max] = this.filters.dateRange
        result = result.filter(book => {
          const pubDate = new Date(book.publishDate).getTime()
          return pubDate >= min && pubDate <= max
        })
      }
      
      // Apply sorting
      const [sortBy, direction] = this.sortOption.split('-')
      result.sort((a, b) => {
        let comparison = 0
        if (sortBy === 'title') {
          comparison = a.title.localeCompare(b.title)
        } else if (sortBy === 'author') {
          comparison = a.author.localeCompare(b.author)
        } else if (sortBy === 'date') {
          comparison = new Date(a.publishDate) - new Date(b.publishDate)
        }
        return direction === 'asc' ? comparison : -comparison
      })
      
      return result
    },
    paginatedBooks() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredBooks.slice(start, end)
    }
  },
  created() {
    this.fetchBooks()
  },
  methods: {
    async fetchBooks() {
      this.loading = true
      try {
        // Replace with actual API call
        const response = await fetch('/api/books')
        this.books = await response.json()
      } catch (error) {
        console.error('Error fetching books:', error)
        this.$message.error('Failed to load books. Please try again later.')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
    },
    handleSort() {
      this.currentPage = 1
    },
    handleFilterChange(filters) {
      this.filters = filters
      this.currentPage = 1
    },
    handlePageChange(page) {
      this.currentPage = page
      // Scroll to top when page changes
      window.scrollTo({ top: 0, behavior: 'smooth' })
    },
    viewBookDetails(bookId) {
      this.$router.push(`/books/${bookId}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.book-list-container {
  padding: 16px;
}

.filter-wrapper {
  margin-bottom: 16px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .search-sort-container {
    display: flex;
    flex: 1;
    
    .search-input {
      margin-right: 12px;
      max-width: 300px;
    }
    
    .sort-select {
      width: 140px;
    }
  }
}

.book-list {
  &.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 16px;
  }
  
  &.list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

@media screen and (max-width: 768px) {
  .list-header {
    flex-direction: column;
    align-items: stretch;
    
    .search-sort-container {
      margin-bottom: 12px;
    }
    
    .view-toggle {
      align-self: flex-end;
    }
  }
  
  .book-list {
    &.grid {
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 12px;
    }
  }
}
</style> 